package com.template;

import java.util.Arrays;

/**
 * 二分查找，从有序数组中查询指定位置
 *
 * @author shenb
 * @date 2022-02-22 22:09
 */
public class _1_BinarySearch {

  public static int searchIndex(int[] array, int value) {
    int left = 0;
    int right = array.length;
    while (left < right) {
      int mid = left + ( (right - left) >> 1);
      if (value < array[mid]) {
        right = mid ;
      } else if (value > array[mid]) {
        left = mid + 1;
      } else {
        return mid;
      }
    }
    return -1;
  }

  public static void main(String[] args) {
        for (int i = 0; i < 1000; i++) {
          int[] ints = Random.randomSortInts();
          int j = searchIndex(ints, 8);
          System.out.println(Arrays.toString(ints) + ", find 8 at index: " + j);
        }
//
//    int i = searchIndex(new int[]{1, 2, 2, 5, 6, 7, 8}, 8);
//    System.out.println(i);
  }
}
